package com.hanson.controller;

import com.hanson.common.bean.ResultMessage;
import com.hanson.common.bean.UserDto;
import com.hanson.common.exception.BusinessException;
import com.hanson.common.service.RedisService;
import com.hanson.common.service.ValidateCodeService;
import com.hanson.common.util.BusinessUtil;
import com.hanson.entity.UserBean;
import com.hanson.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Slf4j
@Controller
@RequestMapping("/admin")
public class AdminController {
    @Autowired
    private UserService userService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private ValidateCodeService validateCodeService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private ApplyCashOutService applyCashOutService;
    @Autowired
    private WeiXinNotifyService weiXinNotifyService;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login(ModelMap modelMap) {
        return "admin/login/login";
    }

    @RequestMapping(value = "/userInfo", method = RequestMethod.GET)
    public String userInfo(ModelMap modelMap, HttpServletRequest request) {
        String token = BusinessUtil.getCookieToken(request, "token");
        UserBean userBean = (UserBean) redisService.get("LOGIN:" + token);
        modelMap.put("user", userService.selectById(String.valueOf(userBean.getId())));
        return "admin/index/userInfo";
    }

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(ModelMap modelMap, HttpServletRequest request) {
        UserDto userDto = new UserDto();
        String token = BusinessUtil.getCookieToken(request, "token");
        if (!StringUtils.isEmpty(token)) {
            UserBean userBean = (UserBean) redisService.get("LOGIN:" + token);
            if (userBean != null && null != userBean.getId()) {
                userDto.setName(StringUtils.isEmpty(userBean.getUserName()) ? userBean.getPhone() : userBean.getUserName());
                String userTypes = userBean.getUserType();
                List<Integer> paramList = new ArrayList();
                if (!StringUtils.isEmpty(userTypes)) {
                    String[] userTypesArray = userTypes.split(",");
                    Arrays.stream(userTypesArray).forEach(type -> {
                        paramList.add(Integer.parseInt(type));
                    });
                }
                userDto.setMenus(menuService.getMenus(paramList));
                userDto.setUserType(userBean.getUserType());
            }
        }
        modelMap.put("activeUser", userDto);
        return "admin/index/index";
    }

    @RequestMapping(value = "/main", method = RequestMethod.GET)
    public String main(ModelMap modelMap) {
        modelMap.put("order", orderService.statisOrder(0));
        modelMap.put("alarmGoods", goodsService.statisAlarmGoods());
        modelMap.put("cashDeal", applyCashOutService.statisDeal());
        modelMap.put("yesTodayMoney", weiXinNotifyService.statisMoney(1));
        modelMap.put("monthMoney", weiXinNotifyService.statisMoney(2));
        modelMap.put("todayUser", userService.statisUser(1));
        modelMap.put("monehUser", userService.statisUser(2));
        return "admin/index/main";
    }


    @RequestMapping(value = "/images/captcha", method = RequestMethod.GET)
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        validateCodeService.create(request, response);
    }

    @RequestMapping(value = "login", method = RequestMethod.POST)
    @ResponseBody
    public ResultMessage login(@RequestBody UserBean userBean, HttpServletRequest request, HttpServletResponse response) {
        ResultMessage resultMessage = new ResultMessage();
        HttpSession session = request.getSession();
        validateCodeService.check(session.getId(), userBean.getVerifyCode());
        if (StringUtils.isEmpty(userBean.getUserName()) || StringUtils.isEmpty(userBean.getPassword())) {
            throw new BusinessException("用户名或密码为空");
        }
        UserBean returnUser = userService.getByNameAndPwd(userBean.getUserName(), userBean.getPassword());
        if (null == returnUser) {
            throw new BusinessException("用户名或密码不正确");
        }
        String token = UUID.randomUUID().toString();
        redisService.set("LOGIN:" + token, returnUser, 60 * 60L);
        Cookie userCookie = new Cookie("token", token);
        //存活期30分钟
        userCookie.setMaxAge(60 * 60 * 24);
        userCookie.setPath("/");
        response.addCookie(userCookie);
        return resultMessage;
    }

    @RequestMapping(value = "updateUserInfo", method = RequestMethod.POST)
    @ResponseBody
    public ResultMessage updateUserInfo(@RequestBody UserBean userBean) {
        ResultMessage resultMessage = new ResultMessage();
        UserBean returnBean = userService.selectById(String.valueOf(userBean.getId()));
        if (!StringUtils.isEmpty(userBean.getPassword()) &&
                !StringUtils.isEmpty(userBean.getNewPwd()) &&
                !StringUtils.isEmpty(userBean.getNewPwdOk())) {
            if (!returnBean.getPassword().equals(userBean.getPassword())) {
                throw new BusinessException("原密码输入不正确！");
            }
            if (!userBean.getNewPwd().equals(userBean.getNewPwdOk())) {
                throw new BusinessException("两次新密码不一致！");
            }
            userBean.setPassword(userBean.getNewPwd());
        }
        userService.updateUser(userBean);
        return resultMessage;
    }

    @RequestMapping(value = "/loginout", method = RequestMethod.GET)
    public String loginout(HttpSession httpSession) {
        if (null != httpSession) {
            httpSession.invalidate();
        }
        return "redirect:/admin/login";
    }
}
